package tgc.edu.tgq.demo.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.tgq.demo.custom.BaseService;
import tgc.edu.tgq.demo.entity.Course;
import tgc.edu.tgq.demo.entity.Grade;
import tgc.edu.tgq.demo.entity.Student;
import tgc.edu.tgq.demo.entity.TbClass;
import tgc.edu.tgq.demo.service.CourseService;
import tgc.edu.tgq.demo.service.GradeService;
import tgc.edu.tgq.demo.service.StudentService;
import tgc.edu.tgq.demo.service.TbClassService;

@Controller
@RequestMapping(value = "/classGrade")
//---------班级成绩录入------------
public class ClassGradeController {
	@Autowired
	private TbClassService classService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private GradeService gradeService;
	//---------表头查找所有班级课程名字-----
	@RequestMapping(value = "manage")
	public void list(ModelMap modelMap) {
		List<TbClass> tbClass=classService.findAll();
		List<Course> course=courseService.findAll();
		modelMap.put("tbClass", tbClass);
		modelMap.put("course", course);
	}
	
	//------------显示表格-------------
	@RequestMapping(value = "/table")
	public String getClassGrade(Integer bjId,Integer kcId,ModelMap modelMap) {
		List<Student> students=studentService.findByTbClassId(bjId);
		List<Grade> grades=new ArrayList<Grade>();
		for (Student stu : students) {
			Grade grade=gradeService.findByStudentIdAndCourseId(stu.getId(),kcId);
			if(grade==null) {
				Grade g=new Grade();
				g.setCourse(courseService.findById(kcId));
				g.setStudent(studentService.findById(stu.getId()));
				gradeService.save(g);
				grades.add(g);
			}else {
				grades.add(grade);
			}
		}
		modelMap.put("grades", grades);
		return "classGrade/table";
	}
	
	@RequestMapping(value = "cjChange")
	@ResponseBody
	public void cjChange(Integer id,Integer grade) {
		Grade g=gradeService.findById(id);
		g.setGrade(grade);
		gradeService.save(g);
	}
}
